package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.Progress;
import com.smedi.ismedi.progress.core.domain.repository.FileRepository;
import com.smedi.ismedi.progress.core.domain.repository.KeyTaskRepository;
import com.smedi.ismedi.progress.core.domain.repository.MliestoneRepository;
import com.smedi.ismedi.progress.core.domain.repository.ProgressProjectRepository;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.ProgressDetailEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.ProgressEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProgressDetailMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProgressMapper;
import com.smedi.ismedi.progress.core.port.adapter.service.ProjectRemoteService;
import com.smedi.ismedi.web.starter.common.PaginationData;
import com.smedi.ismedi.web.starter.common.ResponseData;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 关键任务分页 实现类
 *
 * @author liaojiajie
 * @date 2022/09/19
 */
@Repository
@AllArgsConstructor
@Slf4j
public class KeyTaskRepositoryImpl implements KeyTaskRepository {
    private final AdapterConverter adapterConverter;
    private final FileRepository fileRepository;
    private final AuthorityUtil authorityUtil;
    private final ProgressProjectRepository progressProjectRepository;
    private final ProjectRemoteService projectRemoteService;
    private final ProgressMapper progressMapper;
    private final ProgressDetailMapper progressDetailMapper;


    @Override
    public Page<Progress> getKeyTaskPage(Long offset, Long pageSize,Long hrOrganizationId, Integer projectId, String projectManager, Integer mainCourtyardId, Integer status, String projectCategory,String projectName) {
        Page<ProgressEntity> progressEntity = new Page<>(offset,pageSize);
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        List<ProjectBasicResponse> projectListData = new ArrayList<>();
        List<ProjectBasicResponse> allProjectBasicList = projectRemoteService.getAllProjectBasicList();
        if (mainCourtyardId == null  && hrOrganizationId!=null) {
            projectList = progressProjectRepository.getProjectList(hrOrganizationId);
        }
        if (mainCourtyardId != null) {
            projectList = progressProjectRepository.getProjectList(mainCourtyardId.longValue());
        }
        List<ProjectBasicResponse> data = projectList.getData();
        if(data != null){
            projectListData = data.stream().filter(v -> {
                if (StringUtils.isNotBlank(projectCategory)) {
                    return projectCategory.equals(v.getProjectCategory());
                }
                return true;
            }).filter(v -> {
                //web 端的项目经理筛选
                if (StringUtils.isNotBlank(projectManager)) {
                    return v.getProjectManager().indexOf(projectManager) > -1;
                }
                return true;
            }).filter(v -> {
                //app根据 名称 或者 经理 筛选
                if (StringUtils.isNotBlank(projectName)) {
                    if (v.getProjectName().indexOf(projectName) > -1){
                        return true;
                    }
                    return v.getProjectManager().indexOf(projectName) > -1;
                }
                return true;
            }).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(projectListData)){
                ids =projectListData.stream().map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
            }
        }
        //如果企业组织id下没有项目   则没有项目计划
        if (hrOrganizationId !=null && CollectionUtils.isEmpty(projectListData)){
            return new Page<>();
        }
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(ids),ProgressEntity::getProjectId,ids);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId),ProgressEntity::getProjectId,projectId);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(status),ProgressEntity::getTaskProgressStatus,status);

        lambdaQueryWrapper.orderByAsc(ProgressEntity::getTaskProgressStatus);
        Page<ProgressEntity> progressEntityPage = progressMapper.selectPage(progressEntity, lambdaQueryWrapper);
        List<ProjectBasicResponse> List = projectListData;
        List.forEach(v->{
            for (ProjectBasicResponse projectBasicResponse: allProjectBasicList){
                if (projectBasicResponse.getHrOrganizationId().equals(v.getHrOrganizationId())){
                    v.setHrOrganizationFullName(projectBasicResponse.getHrOrganizationFullName());
                }
            }
        });
        Page<Progress> progressPage = adapterConverter.progressEntityPageToProgress(progressEntityPage);
        //设置项目表那边的 名称 等等字段
        if (hrOrganizationId != null &&  List.size()>0) {
            progressPage.getRecords().forEach(v -> {
                for (ProjectBasicResponse projectBasicResponse: List){
                    if (v.getProjectId().equals(projectBasicResponse.getProjectId())) {
                        v.setName(projectBasicResponse.getProjectName());
                        v.setEngineerType(projectBasicResponse.getProjectCategory());
                        v.setGeneralManager(projectBasicResponse.getProjectManager());
                        v.setMainCourtyard(projectBasicResponse.getHrOrganizationFullName());
                        break;
                    }
                }
            });
        }
        //app端 项目视角
        else if (hrOrganizationId == null && CollectionUtils.isEmpty(data)){
            ProjectBasicResponse project = progressProjectRepository.getProject(projectId.longValue());
            if (StringUtils.isNotBlank(projectCategory) && !project.getProjectCategory().equals(projectCategory) || StringUtils.isNotBlank(projectName) && (project.getProjectName().indexOf(projectName) == -1 && project.getProjectManager().indexOf(projectName) == -1) || StringUtils.isNotBlank(projectManager) && project.getProjectManager().indexOf(projectManager) == -1){
                return new Page<>();
            }
            progressPage.getRecords().forEach(v -> {
                v.setName(project.getProjectName());
                v.setEngineerType(project.getProjectCategory());
                v.setGeneralManager(project.getProjectManager());
                v.setMainCourtyard(project.getHrOrganizationFullName());
            });
        }

        //关键任务进度状态，只判断未完成的任务是否有滞后
        progressPage.getRecords().forEach(v -> {
            LambdaQueryWrapper<ProgressDetailEntity> detailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectScheduleId,v.getId());
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getProjectId,v.getProjectId());
            detailEntityLambdaQueryWrapper.like(ProgressDetailEntity ::getType,"1");
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getCompletion,0);
            detailEntityLambdaQueryWrapper.eq(ProgressDetailEntity ::getStatus,0);
            List<ProgressDetailEntity> detailEntityList = progressDetailMapper.selectList(detailEntityLambdaQueryWrapper);
            if(detailEntityList.size()>0){
                v.setTaskProgressStatus(0);
            }else{
                v.setTaskProgressStatus(1);
            }
        });

        return progressPage;
    }
}
